package com.wxxymakers.grademark.controller;

import com.wxxymakers.grademark.model.entity.WxItem;
import com.wxxymakers.grademark.service.WxItemService;
import com.wxxymakers.grademark.utils.RestResponse;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

/**
 * @AUTHOR soft
 * @DATE 2018/12/31 1:57
 * @DESCRIBE
 */
@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private WxItemService itemService;

    /**
     * 项目的添加
     * 需要超级管理员或者学院管理员的权限
     * @param item 项目信息
     */
    @PostMapping("/add")
    @RequiresRoles(value = {"admin", "college-admin"}, logical = Logical.OR)
    public RestResponse add(@RequestBody WxItem item) {
        item.setPlaces(item.getPlaces());
        item.setRanks(item.getRanks());
        if (itemService.add(item, item.getRanks(), item.getPlaces())) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    /**
     * 根据id删除项目
     * @param id 项目id
     */
    @PostMapping("/delete/{id}")
    @RequiresRoles(value = {"admin", "college-admin"}, logical = Logical.OR)
    public RestResponse delete(@PathVariable int id) {
        if (itemService.delete(id)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    /**
     * 修改项目 依据项目id
     * @param item 项目修改信息
     */
    @PostMapping("/change")
    @RequiresRoles(value = {"admin", "college-admin"}, logical = Logical.OR)
    public RestResponse change(@RequestBody WxItem item) {
        item.setRanks(item.getRanks());
        item.setPlaces(item.getPlaces());
        if (itemService.change(item)) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

    /**
     * 根据id获取项目信息
     * @param id 项目id
     */
    @PostMapping("/get/{id}")
    public RestResponse get(@PathVariable int id) {
        WxItem wxItem = itemService.byId(id);
        if (wxItem != null) {
            return RestResponse.ok(wxItem);
        }
        return RestResponse.fail();
    }

    /**
     * 项目分页查询
     * @param page 页码
     * @param limit 尺寸
     * @param item 查询条件
     */
    @PostMapping("/page")
    public RestResponse page(int page, int limit, WxItem item) {
        Page<WxItem> wxItems = itemService.page(page, limit, item);
        if (wxItems != null) {
            return RestResponse.ok(wxItems);
        }
        return RestResponse.fail();
    }
}
